package com.zyf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyf.client.HospitalFeignClient;
import com.zyf.common.excption.YyghException;
import com.zyf.common.helper.HttpRequestHelper;
import com.zyf.common.result.ResultCodeEnum;
import com.zyf.enums.OrderStatusEnum;
import com.zyf.enums.PaymentStatusEnum;
import com.zyf.enums.PaymentTypeEnum;
import com.zyf.mapper.PaymentInfoMapper;
import com.zyf.model.order.OrderInfo;
import com.zyf.model.order.PaymentInfo;
import com.zyf.service.OrderInfoService;
import com.zyf.service.PaymentInfoService;
import com.zyf.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/** 支付订单 业务层实现类
 * @author zyf
 * @date 2021年06月02日 17:46
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper,PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    /**
     * 向支付记录表里添加信息
     * @author zyf
     * @date 2021/6/2 17:51
     * @param order 订单信息
     * @param status  支付方式
     */
    @Override
    public void savePaymentInfo(OrderInfo order, Integer status) {
        //根据订单id和支付类型查询支付订单表中是否有该条数据
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",order.getId())
                .eq("payment_type",status);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0){
            return;
        }
        //添加记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderId(order.getId())
                .setPaymentType(status)
                .setOutTradeNo(order.getOutTradeNo())
                .setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus())
                .setCreateTime(new Date());
        String subject = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd") + "|" + order.getHosname() + "|" + order.getDepname() + "|" + order.getTitle();
        paymentInfo.setSubject(subject)
                .setTotalAmount(order.getAmount());
        baseMapper.insert(paymentInfo);
    }

    /**
     * 更新订单状态
     * @author zyf
     * @date 2021/6/3 17:03
     * @param outTradeNo 对外业务编号
     * @param map 微信接口返回的map集合
     */
    @Override
    public void paySuccess(String outTradeNo, Map<String, String> map) {
        //1、根据订单编号得到支付记录
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no",outTradeNo)
                .eq("payment_type",PaymentTypeEnum.WEIXIN.getStatus());
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);

        //2、更新支付记录
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus())
                .setCallbackTime(new Date())
                .setTradeNo(map.get("transaction_id"))
                .setCallbackContent(map.toString());
        baseMapper.updateById(paymentInfo);

        //3、根据订单号得到订单信息
        OrderInfo orderInfo = orderInfoService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());

        //4、更新订单信息
        orderInfoService.updateById(orderInfo);

        //5、调用医院接口，更新订单支付信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign",sign);
        JSONObject request = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if(request.getInteger("code") != 200) {
            throw new YyghException(request.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }

    /**
     * 获取支付记录
     * @author zyf
     * @date 2021/6/3 18:32
     * @param orderId 订单Id
     * @param paymentType 支付状态
     * @return com.zyf.model.order.PaymentInfo
     */
    @Override
    public PaymentInfo getPaymentInfo(String orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId)
                .eq("payment_type",paymentType);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);

        return paymentInfo;
    }
}
